#include "printpreview.h"
#include "printwindow.h"
#include <QPainter>
#include <QPaintEvent>
#include <QImage>

/*PrintPreview::PrintPreview(PioCore * core, QWidget * parent) :
    QWidget(parent), m_core(core), m_width(3), m_height(4), m_zoom(0.25), m_page_count(1), m_page(0), m_quit(false), m_thread(this), m_autorotate(false)
{
    m_paper_width = 21.0;
    m_paper_height = 29.7;
    m_thread.start();
}

PrintPreview::~PrintPreview()
{
    m_mutex.lock();
    m_quit = true;
    m_cond.wakeAll();
    m_mutex.unlock();
    m_thread.wait();
}

void PrintPreview::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    painter.drawText(16, 32, QString("%1/%2").arg(m_page+1).arg(m_page_count));

    painter.translate(width() / 2, height() / 2);
    painter.scale(m_zoom, m_zoom);
    painter.translate(toPixels(1 - m_paper_width / 2), toPixels(1 - m_paper_height / 2));
    painter.fillRect(toPixels(-1), toPixels(-1), toPixels(m_paper_width), toPixels(m_paper_height), Qt::white);

    m_mutex.lock();
    QVector<ImageRow> rows = m_rows;
    m_mutex.unlock();

    double y = 0;
    for(int i = 0; i < rows.size(); i++) {
        ImageRow & row = rows[i];
        if(row.page != m_page)
            continue;
        double x = 0;
        for(int i = 0; i < row.images.size(); i++) {
            QImage & img = row.images[i];
            painter.drawImage(toPixels(x), toPixels(y), img);
            x += toCentimeters(img.width()) + 1;
        }
        y += row.height + 1;
    }
}

void PrintPreview::updateSize()
{
    QSize mysize(toPixels(m_paper_width * m_zoom), toPixels(m_paper_height * m_zoom));
    if(mysize.width() < m_scrollarea.width())
        mysize.setWidth(m_scrollarea.width());
    if(mysize.height() < m_scrollarea.height())
        mysize.setHeight(m_scrollarea.height());
    setFixedSize(mysize);
    setMinimumSize(mysize);
    update();
}

void PrintPreview::setup()
{
    QMutexLocker ml(&m_mutex);
    QVector<QImage> images;
    foreach(MediaItem::Metadata item, m_selection) {
        QImage & img = m_images[item.filename].image;
        if(!img.isNull())
            images.append(img);
    }
    ml.unlock();

    double width = m_paper_width - 2;
    double height = m_paper_height - 2;
    double margin = 1;

    QVector<ImageRow> rows;

    for(int i = 0; i < images.size(); i++) {
        if(rows.empty() || rows.back().width + margin + toCentimeters(images[i].width()) > width) {
            ImageRow row;
            row.images.append(images[i]);
            row.width = toCentimeters(images[i].width());
            row.height = toCentimeters(images[i].height());
            row.hspace = width - row.width;
            rows.append(row);
        }
        else {
            ImageRow & row = rows.back();
            row.images.append(images[i]);
            row.width += margin + toCentimeters(images[i].width());
            row.height = std::max(row.height, toCentimeters(images[i].height()));
            row.hspace -= toCentimeters(images[i].width());
        }
    }

    double y = 0;
    int page_count = 1;
    for(int i = 0; i < rows.size(); i++) {
        ImageRow & row = rows[i];
        if(y > 0 && y + row.height > height) {
            page_count++;
            y = 0;
        }
        row.page = page_count - 1;
        y += row.height + 1;
    }

    ml.relock();
    m_rows = rows;
    m_page_count = page_count;
    emit pages(page_count);
    ml.unlock();
    update();
}

double PrintPreview::toCentimeters(int pixels)
{
    return pixels / 300.0 * 2.54;
}

int PrintPreview::toPixels(double centimeters)
{
    return centimeters * 300.0 / 2.54;
}

void PrintPreview::setSelection(QList<MediaItemPtr> selection)
{
    QMutexLocker ml(&m_mutex);
    m_selection.clear();
    foreach(MediaItemPtr item, selection)
        m_selection.append(item->metadata());
    m_cond.wakeAll();
}

void PrintPreview::setScrollArea(QSize size)
{
    m_scrollarea = size;
    updateSize();
}

void PrintPreview::previousPage()
{
    m_page = std::max(m_page - 1, 0);
    update();
}

void PrintPreview::nextPage()
{
    m_page = std::min(m_page + 1, m_page_count - 1);
    update();
}

void PrintPreview::zoom(double zoom)
{
    m_zoom = zoom;
    updateSize();
}

void PrintPreview::zoomIn()
{
    zoom(std::min(2.0, m_zoom * 2));
}

void PrintPreview::zoomOut()
{
    zoom(std::max(0.125, m_zoom / 2));
}

void PrintPreview::setPaperSize(double width, double height)
{
    m_paper_width = width;
    m_paper_height = height;
    updateSize();
    setup();
}

void PrintPreview::setAutoRotate(bool rotate)
{
    m_mutex.lock();
    m_autorotate = rotate;
    m_cond.wakeAll();
    m_mutex.unlock();
}

void PrintPreview::run()
{
    QMutexLocker ml(&m_mutex);
    while(!m_quit) {
        bool changed = false;
        QList<QString> keys = m_images.keys();
        foreach(QString str, keys) {
            bool found = false;
            foreach(MediaItem::Metadata m, m_selection) {
                if(m.filename == str) {
                    found = true;
                    break;
                }
            }
            if(!found) {
                m_images.remove(str);
                ml.unlock();
                setup();
                ml.relock();
                changed = true;
            }
        }
        if(changed || m_quit)
            continue;

        QSize isize(toPixels(m_width), toPixels(m_height));
        foreach(MediaItem::Metadata m, m_selection) {
            ImageInfo & ii = m_images[m.filename];
            bool fit_rotation = m_autorotate;
            bool portrait = (m_height > m_width);
            if(ii.image.size() != isize || (fit_rotation && (portrait != ii.portrait && !ii.rotated)) || (!fit_rotation && ii.rotated)) {
                ml.unlock();
                QImage image = m_core->load(m.filename, QSize());
                ii.portrait = (image.height() > image.width());
                int o = 0;
                if(o & 1)
                    ii.portrait = !ii.portrait;
                if(fit_rotation && (portrait != ii.portrait)) {
                    o = (o + 1) % 4;
                    ii.rotated = true;
                }
                else
                    ii.rotated = false;

                QSize size = isize;
                if(o & 1)
                    size = QSize(size.height(), size.width());
                image = image.scaled(size, Qt::KeepAspectRatioByExpanding);
                image = image.copy((image.width() - size.width()) / 2, (image.height() - size.height()) / 2, size.width(), size.height());
                if(o) {
                    QTransform transform;
                    transform.rotate(90 * o);
                    image = image.transformed(transform);
                }
                ml.relock();
                ii.image = image;
                ml.unlock();
                setup();
                ml.relock();
                changed = true;
            }
        }
        if(changed || m_quit)
            continue;
        m_cond.wait(&m_mutex);
    }
}

PrintPreview::Thread::Thread(PrintPreview *preview)
    : m_preview(preview)
{
}

void PrintPreview::Thread::run()
{
    m_preview->run();
}
*/
